/*
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <http://www.gnu.org/licenses/>.
 */
package daemonClient;

import java.rmi.UnexpectedException;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class Sifrovani
{
	public static String phrase = "";

	public static String encrypt(String text) throws UnexpectedException
	{
		if (phrase == "")
			throw new UnexpectedException("Phrase is not set.");

		try
		{
			DESKeySpec keySpec = new DESKeySpec(phrase.getBytes("UTF8"));
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
			SecretKey key = keyFactory.generateSecret(keySpec);
			sun.misc.BASE64Encoder base64encoder = new BASE64Encoder();
			// ENCODE plainTextPassword String
			byte[] cleartext = text.getBytes("UTF8");
			Cipher cipher = Cipher.getInstance("DES"); // cipher is not thread
														// safe
			cipher.init(Cipher.ENCRYPT_MODE, key);
			return base64encoder.encode(cipher.doFinal(cleartext));
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return null;
	}

	public static String decrypt(String s) throws UnexpectedException
	{
		if (phrase == "")
			throw new UnexpectedException("Phrase is not set.");
		
		if(s == null)
			return null;
		try
		{
			sun.misc.BASE64Decoder base64decoder = new BASE64Decoder();
			// DECODE encryptedPwd String
			byte[] encrypedPwdBytes = base64decoder.decodeBuffer(s);
			DESKeySpec keySpec = new DESKeySpec(phrase.getBytes("UTF8"));
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
			SecretKey key = keyFactory.generateSecret(keySpec);
			Cipher cipher = Cipher.getInstance("DES");// cipher is not thread
														// safe
			cipher.init(Cipher.DECRYPT_MODE, key);
			byte[] plainTextPwdBytes = (cipher.doFinal(encrypedPwdBytes));
			return new String(plainTextPwdBytes);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return null;
	}
	
	public static void setPhrase(String Phase)
	{
		phrase = Phase;
	}
	
	public static boolean isPhraseSet()
	{
		return phrase != "";
	}
}
